<template>
  <div>
    <div v-if="dataList.length == 0">
      <div class="chart-title">{{ options.title.text }}</div>
      <a-empty :image="simpleImage" />
    </div>
    <chart :options="options" v-else :style="{ height: height + 'px' }"></chart>
  </div>
</template>
<script>
import { Empty } from 'ant-design-vue';
import { requestHttp, maccApi, fillTimeLineData } from '@utils/index';
import publicChart from './publicChart.vue';
import moment from 'moment-timezone';
import { mapState } from 'vuex';
export default {
  name: 'IntfFlowTrend',
  props: {
    deviceInfo: {
      type: Object,
      default: () => {},
    },
    timeRange: {
      type: Object,
      default: () => {
        return {
          end: +new Date(),
          start: +new Date() - 48 * 3600 * 1000,
        };
      },
    },
    intf: {
      type: String,
      default: '',
    },
    showTitle: {
      type: Boolean,
      default: false,
    },
    height: {
      type: Number,
      default: 250,
    },
  },
  components: {
    chart: publicChart,
  },
  data() {
    return {
      options: {
        title: {
          text: '',
        },
      },
      dataList: [],
      dataType: 'hour',
    };
  },
  computed: {
    ...mapState('I18n', ['lang']),
    timezone() {
      const currentGroup =
        this.$store.state.Group.groupMap[this.deviceInfo.groupId];
      return (currentGroup && currentGroup.timezone) || '';
    },
    api() {
      const gatewayApi = `${maccApi.EGW_FLOWTREND_GET_API}?sn=${this.deviceInfo.serialNumber}&intf_name=${this.intf}&start=${this.timeRange.start}&end=${this.timeRange.end}`;
      const otherApi = `${maccApi.DEVICE_MULTIINTERFACEFLOW_GET_API}?sn=${this.deviceInfo.serialNumber}&intf_shorts=${this.intf}&start=${this.timeRange.start}&end=${this.timeRange.end}`;
      return ['GATEWAY', 'WR'].includes(this.deviceInfo.commonType)
        ? gatewayApi
        : otherApi;
    },
    keyfiled() {
      return ['GATEWAY', 'WR'].includes(this.deviceInfo.commonType)
        ? 'list'
        : this.intf;
    },
    filed() {
      return ['GATEWAY', 'WR'].includes(this.deviceInfo.commonType)
        ? { down: 'inputRate', up: 'outputRate' }
        : { down: 'downRate', up: 'upRate' };
    },
  },
  beforeCreate() {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  },
  mounted() {
    this.initChartOptions();
  },

  watch: {
    deviceInfo: {
      handler() {
        this.initChartOptions();
      },
      deep: true,
    },
    timeRange: {
      handler() {
        this.initChartOptions();
      },
      deep: true,
    },
    intf() {
      this.initChartOptions();
    },
  },
  methods: {
    async initChartOptions() {
      if (!this.intf) {
        this.dataList = [];
        return;
      }
      const res = await requestHttp({
        api: this.api,
        method: 'GET',
        module: 'logbiz',
      });
      this.dataType = this.getTiemType(
        this.timeRange.start,
        this.timeRange.end
      );
      let dataIntervalSeconds, maxMissingIntervalSeconds;
      if (this.dataType == 'minute' || this.dataType == 'hour') {
        dataIntervalSeconds = 300;
        maxMissingIntervalSeconds = 3000;
      } else if (this.dataType == 'week') {
        dataIntervalSeconds = 1800;
        maxMissingIntervalSeconds = 30000;
      } else if (this.dataType == 'month') {
        dataIntervalSeconds = 2 * 3600;
        maxMissingIntervalSeconds = 9000;
      }

      if (res && res.code == 0) {
        const list =
          (this.keyfiled == 'list'
            ? res[this.keyfiled]
            : res.map[this.keyfiled]) || [];
        this.dataList = list;
        const chartData = fillTimeLineData(
          list,
          this.timeRange.start,
          this.timeRange.end,
          'gatherTime',
          dataIntervalSeconds,
          maxMissingIntervalSeconds
        );
        const chartFormatData = this.formatterChartData(chartData);
        //this.options = this.getChartOptions(chartFormatData);
        this.$set(this, 'options', this.getChartOptions(chartFormatData));
      } else {
        this.$message.error(res.msg || this.$t('deviceDetail.getDataFail'));
      }
    },
    formatterChartData(list) {
      const chartData = {
        gatherTime: [],
        downRate: [],
        upRate: [],
      };
      list.forEach((item) => {
        chartData.gatherTime.push(
          //new Date(item.gatherTime).Format('YYYY/MM/DD hh:mm:ss')
          item.gatherTime
          // moment
          //   .tz(item.gatherTime, this.timezone)
          //   .format('YYYY/MM/DD HH:mm:ss')
        );
        if (item[this.filed.down] != undefined) {
          chartData.downRate.push(
            (
              item[this.filed.down] /
              (['GATEWAY'].includes(this.deviceInfo.commonType)
                ? 1024 * 1024
                : 128)
            ).toFixed(2)
          );
        } else {
          chartData.downRate.push(`-`);
        }
        if (item[this.filed.up] != undefined) {
          chartData.upRate.push(
            (
              item[this.filed.up] /
              (['GATEWAY'].includes(this.deviceInfo.commonType)
                ? 1024 * 1024
                : 128)
            ).toFixed(2)
          );
        } else {
          chartData.upRate.push(`-`);
        }
      });
      return chartData;
    },
    getChartOptions(chartData) {
      let showTick = '';
      let option = {
        title: {
          text: this.getChartTitle(),
          textStyle: {
            fontSize: 14,
            fontStyle: 'normal',
            fontWeight: 'bolder',
          },
        },
        color: ['#9eb0fe', '#57c8ed'],
        grid: {
          left: '8%',
          right: '5%',
          bottom: '10%',
        },
        legend: {
          data: [
            this.$t('deviceDetail.commonUplink'),
            this.$t('deviceDetail.commonDownlink'),
          ],
          right: '3%',
          top: '5%',
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left',
            color: 'rgba(255,255,255,1)',
          },
          backgroundColor: 'rgba(0,0,0,0.5)', //设置背景图片 rgba格式
          borderWidth: 0,
          padding: 5,
          formatter: (params) => {
            let res = '';
            let restop = '';
            for (let i = 0; i < params.length; i++) {
              const timeString = moment(Number(params[i].axisValue))
                .tz(this.timezone)
                .format('YYYY/MM/DD HH:mm:ss');
              restop = '<span>' + timeString + '</span><br/>';
              res +=
                '<span>' +
                params[i].marker +
                params[i].seriesName +
                ' : ' +
                params[i].data +
                '</span><br/>';
            }
            return restop + res;
          },
          axisPointer: {
            type: 'cross',
            animation: false,
            label: {
              backgroundColor: '#505765',
              formatter: (params) => {
                if (params.axisDimension == 'x') {
                  return moment
                    .tz(Number(params.value), this.timezone)
                    .format('YYYY/MM/DD HH:mm:ss');
                } else {
                  return params.value;
                }
              },
            },
          },
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLine: {
            onZero: false,
          },
          axisTick: {
            show: true,
          },
          axisLabel: {
            // formatter: function (value) {
            //   let timearr = value
            //     .replace(' ', '/')
            //     .replace(/:/g, '/')
            //     .split('/');
            //   let timestr = `${timearr[3]}:${timearr[4]}:${timearr[5]}`;
            //   return timestr;
            // },
            formatter: (value) => {
              return this.getGatherTime(value);
            },
          },
          data: chartData.gatherTime,
        },
        yAxis: [
          {
            name: this.$t('deviceDetail.avgrate'),
            type: 'value',
            nameTextStyle: {
              align: 'left',
            },
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: this.$t('deviceDetail.commonUplink'),
            type: 'line',
            smooth: true,
            areaStyle: {},
            lineStyle: {
              width: 1,
            },
            data: chartData.upRate,
          },
          {
            name: this.$t('deviceDetail.commonDownlink'),
            type: 'line',
            smooth: true,
            areaStyle: {},
            lineStyle: {
              width: 1,
            },
            data: chartData.downRate,
          },
        ],
      };
      option.xAxis.axisLabel.interval = (index, value) => {
        let show = false;
        const chartTitle = this.timeRange.chartTitle || '';
        switch (this.dataType) {
          case 'hour': {
            if (chartTitle.indexOf(this.$t('dataInsight.last1Hour')) != -1) {
              show = true;
            } else {
              let str = new Date(Number(value)).Format('h');
              if (showTick != str && parseInt(str) % 2 == 0) {
                showTick = str;
                show = true;
              }
            }
            break;
          }
          case 'day': {
            let str = new Date(Number(value)).Format('h');
            if (showTick != str && parseInt(str) % 2 == 0) {
              showTick = str;
              show = true;
            }
            break;
          }
          case 'week': {
            let str = moment(Number(value)).tz(this.timezone).format('ddd');
            console.log('week', showTick, str);
            if (showTick !== str) {
              showTick = str;
              show = true;
            }
            break;
          }
          case 'month': {
            let str = new Date(Number(value)).Format('D');
            if (showTick !== str) {
              showTick = str;
              show = true;
            }
            break;
          }
          case 'minute': {
            show = true;
            break;
          }
        }
        return show;
      };
      return option;
    },
    getChartTitle() {
      return this.showTitle
        ? this.timeRange.chartTitle
          ? this.timeRange.chartTitle + ` ` + this.$t('deviceDetail.flowup')
          : ''
        : '';
    },
    getTiemType(start, end) {
      const item = end - start;
      console.log(item);
      const h = 60 * 60 * 1000;
      if (item <= h) {
        return 'minute';
      }
      const day = h * 24;
      if (item <= day * 2) {
        return 'hour';
      }
      const week = day * 7;
      if (item <= week) {
        return 'week';
      }
      return 'month';
    },
    getGatherTime(value) {
      let str;
      let timeString = '';
      switch (this.dataType) {
        case 'minute':
          str = moment(Number(value)).tz(this.timezone).format('HH:mm');
          break;
        case 'hour':
          str = moment(Number(value)).tz(this.timezone).format('H');
          break;
        case 'day':
          str = moment(Number(value)).tz(this.timezone).format('H');
          break;
        case 'week':
          if (this.lang == 'zh') {
            timeString = moment(Number(value))
              .tz(this.timezone)
              .format('YYYY/MM/DD HH:mm:ss');
            str = new Date(timeString).Format('W');
          } else {
            str = moment(Number(value)).tz(this.timezone).format('ddd');
            console.log(moment(Number(value)).tz(this.timezone), str);
          }

          break;
        case 'month':
          str = moment(Number(value)).tz(this.timezone).format('DD');
          break;
      }
      return str;
    },
  },
};
</script>
<style lang="less" scoped>
.chart-title {
  font-size: 14px;
  font-weight: bolder;
}
</style>
